package com.java.mall_imooc.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.java.mall_imooc.common.utils.PageUtils;
import com.java.mall_imooc.common.utils.R;
import com.java.mall_imooc.entity.Product;
import com.java.mall_imooc.mapper.ProductDao;
import com.java.mall_imooc.service.CategoryService;
import com.java.mall_imooc.service.ProductService;
import com.java.mall_imooc.vo.ProductVo;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service("productService")
@AllArgsConstructor
public class ProductServiceImpl extends ServiceImpl<ProductDao, Product> implements ProductService {
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Product product,Integer pageNum, Integer pageSize) {
        IPage<Product> page = this.page(
                new Page<>(pageNum, pageSize),
                new QueryWrapper<Product>() // 拼接查询条件
        );

        return new PageUtils(page);
    }

    @Override
    public R<PageInfo> getProductsByCategoryId(Integer categoryId, Integer pageNum, Integer pageSize) {
        Set<Integer> categoryIds = new HashSet<>();
        if (categoryId != null) {
            categoryIds = categoryService.subCategoryIds(categoryId);
            categoryIds.add(categoryId);
        }

        // 开始分页
        PageHelper.startPage(pageNum,pageSize);
        List<Product> products = this.baseMapper.selectList(new LambdaQueryWrapper<Product>().eq(Product::getStatus, 1).in(CollectionUtil.isNotEmpty(categoryIds), Product::getCategoryId, categoryIds));
        List<ProductVo> productVos = products
                .stream().map(e -> {
                    ProductVo productVo = new ProductVo();
                    BeanUtils.copyProperties(e, productVo);
                    return productVo;
                }).collect(Collectors.toList());
        PageInfo pageInfo = new PageInfo(products);
        pageInfo.setList(productVos);
        return R.ok(pageInfo);
    }

}